package com.mofang.powerdekorhelper.persenter;

import com.mofang.powerdekorhelper.R;
import com.mofang.powerdekorhelper.base.BasePresent;
import com.mofang.powerdekorhelper.model.NewsInfo;
import com.mofang.powerdekorhelper.utils.UrlTools;
import com.mofang.powerdekorhelper.utils.http.InitRetrofit;
import com.mofang.powerdekorhelper.utils.http.RetrofitSerives;
import com.mofang.powerdekorhelper.view.NewsInfoView;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by luofei on 2017/7/4 0004.
 */

public class NewsInfoPersenter extends BasePresent<NewsInfoView> {

    RetrofitSerives retrofitSerives;

    Call<NewsInfo> newsInfoCall;

    public void getNewsInformation(int page, int pageSize) {

        view.showProgress();
        retrofitSerives = InitRetrofit.getInstance().getRetrofit(UrlTools.NewsUrl);

        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), getJsonParams(page, pageSize));

        newsInfoCall = retrofitSerives.getNewsInfo(body);

        newsInfoCall.enqueue(new Callback<NewsInfo>() {
            @Override
            public void onResponse(Call<NewsInfo> call, Response<NewsInfo> response) {
                if (response.isSuccessful()) {

                    if (response.body().getCode().equals("0")) {

                        if (response.body().getResult() != null) {

                            if (response.body().getResult().getData() != null) {

                                view.setNewsInfomation(response.body());
                            }
                        }
                    } else {
                        view.showErrorLayout(null);
                        view.toast(R.string.net_request_fail);
                    }
                } else {

                    view.showErrorLayout(null);
                    view.toast(R.string.net_request_fail);
                }
            }

            @Override
            public void onFailure(Call<NewsInfo> call, Throwable t) {

                view.showErrorLayout(null);
                view.toast(R.string.net_request_abnormal);

            }
        });


    }

    private String getJsonParams(int page, int pageSize) {

        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("page", page);
            jsonObject.put("pageSize", pageSize);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jsonObject.toString();
    }

    @Override
    public void stopRequest() {

    }
}
